/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 *
 */
package com.lvyh.lightframe.job.admin.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lvyh.lightframe.job.admin.bean.JobAlarmConfigBean;
import com.lvyh.lightframe.job.admin.bean.JobAlarmLogBean;
import com.lvyh.lightframe.job.admin.model.JobAlarmUserParam;
import com.lvyh.lightframe.job.admin.processor.JobManageProcessor;
import com.lvyh.lightframe.job.admin.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class MessageNotifyService {

    private static Logger logger = LoggerFactory.getLogger(MessageNotifyService.class);

    @Autowired
    private JobManageProcessor jobManageProcessor;

    /*
     * Send alarm events to the specified user
     */
    public void sendMessage(JobAlarmConfigBean alarmConfigBean, HashMap<String, String> param, String eventKey) {
        try {
            int objectId = Integer.parseInt(param.get("task_id"));
            String taskName = param.get("task_name");
            String alarmDetail = param.get("alarm_content");

            List<JobAlarmUserParam> alarmUserList = JSONObject.parseArray(alarmConfigBean.getUserContact(), JobAlarmUserParam.class);
            JobAlarmConfigBean updateAlarmConfigBean = new JobAlarmConfigBean();

            boolean usePhone = false;
            boolean useMail = false;

            long currentTime = System.currentTimeMillis();
            long smsLastSendTime = Objects.equals(alarmConfigBean.getSmsLastSendTime(), "0") ? System.currentTimeMillis() : DateUtils.parseDate(alarmConfigBean.getSmsLastSendTime()).getTime();
            long smsIntervalTime = Long.parseLong(alarmConfigBean.getSmsIntervalTime());

            //1440m=86400000ms=24h
            if (smsIntervalTime > 86400000) smsIntervalTime = 86400000;
            // 1200s=20m
            if (smsIntervalTime < 1200000) smsIntervalTime = 1200000;

            if ((currentTime - smsLastSendTime) > smsIntervalTime) {
                updateAlarmConfigBean.setSmsLastSendTime(DateUtils.formatYmdHis(currentTime));
                usePhone = true;
            }
            logger.info((usePhone ? "will be " : "Do not ") + "Send alarm SMS, SMS interval calculation--->Since last sen" + (currentTime - smsLastSendTime) / 1000 + "s");

            long emailLastSendTime = Objects.equals(alarmConfigBean.getEmailLastSendTime(), "0") ? System.currentTimeMillis() : DateUtils.parseDate(alarmConfigBean.getEmailLastSendTime()).getTime();
            long emailIntervalTime = Long.parseLong(alarmConfigBean.getEmailIntervalTime());

            if (emailIntervalTime > 86400000) emailIntervalTime = 86400000;
            // 600s
            if (emailIntervalTime < 600000) emailIntervalTime = 600000;

            if ((currentTime - emailLastSendTime) > emailIntervalTime) {
                updateAlarmConfigBean.setEmailLastSendTime(DateUtils.formatYmdHis(currentTime));
                useMail = true;
            }

            logger.info((useMail ? "will be " : "Do not ") + "Send alarm email, email interval calculation--->Since last sen" + (currentTime - emailLastSendTime) / 1000 + "s");

            if (CollectionUtils.isEmpty(alarmUserList)) {
                return;
            }
            if (!usePhone && !useMail) {
                logger.info("Failed to send alarm information: SMS or email are closed at the same time, and sending is cancelled -> {}", JSON.toJSONString(param));
                return;
            }


            String msg = "";
            if (sendEventMessage(alarmUserList, usePhone, useMail, param, eventKey)) {
                msg = "Alarm message sent successfully -> ";

                updateAlarmConfigBean.setId(alarmConfigBean.getId());
                updateAlarmConfigBean.setUpdateTime(new Date());
                jobManageProcessor.updateJobAlarmConfigBean(updateAlarmConfigBean);
            } else {
                msg = "Alarm message sent failed -> ";
            }
            alarmDetail = msg + alarmDetail;
            JobAlarmLogBean alarmLog = new JobAlarmLogBean();
            alarmLog.setTaskId(objectId);
            alarmLog.setAlarmTime(new Date());
            alarmLog.setAlarmType(alarmConfigBean.getAlarmType());
            alarmLog.setAlarmName(taskName);
            alarmLog.setAlarmDetail(alarmDetail);
            jobManageProcessor.saveJobAlarmLogBean(alarmLog);

        } catch (Exception e) {
            logger.error("Alarm error:{}", e.getMessage());
        }
    }

    public boolean sendEventMessage(List<JobAlarmUserParam> alarmUserList, boolean usePhone, boolean useMail, HashMap<String, String> param, String eventKey) {
        try {
            logger.info("Send alarm info success.");
            return true;
        } catch (Exception e) {
            logger.error("Send alarm info error:{}", e.getMessage());
        }
        return false;
    }


}
